package com.chenglin.dogapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {

    var list = arrayListOf<KeyValueBean>()
    lateinit var dogAdapter: DogAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        list.add(KeyValueBean("1", "张三"))
        list.add(KeyValueBean("2", "李四"))
        list.add(KeyValueBean("3", "王五"))
        list.add(KeyValueBean("4", "赵六"))

        recycler_view.layoutManager = LinearLayoutManager(this)
        dogAdapter = DogAdapter(this)
        dogAdapter.setData(list)
        recycler_view.adapter = dogAdapter


        btn_add.setOnClickListener {
            var newList = ArrayList(list)
            newList.add(KeyValueBean("添加:${System.currentTimeMillis()}","刘老七"))
            var old =  dogAdapter.getOldList()
            val calculateDiff = DiffUtil.calculateDiff(DiffUtilCallBack(old,newList), true)
            dogAdapter.setData(newList);
            calculateDiff.dispatchUpdatesTo(dogAdapter)
            list.clear()
            list.addAll(newList)
        }

        btn_delete.setOnClickListener {
            var newList = ArrayList(list)
            newList.removeAt(list.size -1)
            var old =  dogAdapter.getOldList()
            val calculateDiff = DiffUtil.calculateDiff(DiffUtilCallBack(old,newList), true)
            dogAdapter.setData(newList);
            calculateDiff.dispatchUpdatesTo(dogAdapter)
            list.clear()
            list.addAll(newList)

        }
        btn_change.setOnClickListener {
            var newList = ArrayList(list)
            var old =  dogAdapter.getOldList()
            //直接更改--------- 不变化
//            newList[newList.size-1].id = "更改:${System.currentTimeMillis()}"
//            newList[newList.size-1].name = "更改:${System.currentTimeMillis()}"

            //先删除在添加没问题
            newList.removeAt(newList.size-1)
            newList.add(KeyValueBean("更改:${System.currentTimeMillis()}","更改:${System.currentTimeMillis()}"))

            val calculateDiff = DiffUtil.calculateDiff(DiffUtilCallBack(old,newList), true)
            dogAdapter.setData(newList)
            calculateDiff.dispatchUpdatesTo(dogAdapter)
            list.clear()
            list.addAll(newList)

        }


    }


}